const path = require('path');
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const calcCross = require('./calc-cross');

const globalStore = {
  hmToken: '',
  Cross: '',
};

const app = express();

const tokenIsInvalid = data => {
  return !data.success && data.message?.toLowerCase()?.includes('token');
};

const refreshCookies = async () => {
  const rs = await fetch('https://www.kuwo.cn/rankList');
  const hmToken = rs.headers.get('Set-Cookie')?.split(';').at(0);
  globalStore.hmToken = hmToken;
  globalStore.Cross = calcCross(hmToken?.split('=').at(-1));
};

const getApi = async (url, queryString) => {
  return fetch(`${url}?${queryString}`, {
    headers: {
      csrf: '5RD6CR6I8BO',
      cookie: `kw_token=5RD6CR6I8BO; _ga=GA1.2.848284490.1688864236; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1688864236,1688866179,1689298676; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1689298676; _gid=GA1.2.1494217277.1689298676; _gat=1; _ga_ETPBRPM9ML=GS1.2.1689298676.2.0.1689298676.60.0.0;${globalStore.hmToken}`,
      Referer: 'https://www.kuwo.cn/',
      Cross: globalStore.Cross,
    },
  }).then(r => r.json());
};

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());

// 首页
app.get('/', async (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

// 获取计数
// app.get('/get', async (req, res) => {
//   const url = req.query.url;
//   const query = { ...req.query };
//   const token = query.token;
//   delete query.url;
//   delete query.token;
//   const queryString = new URLSearchParams(Object.entries(query)).toString();
//   const r = await fetch(`${url}?${queryString}`, {
//     headers: {
//       csrf: token,
//       cookie:
//         'kw_token=5RD6CR6I8BO; _ga=GA1.2.848284490.1688864236; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1688864236,1688866179,1689298676; _gid=GA1.2.1494217277.1689298676; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1689299692; _ga_ETPBRPM9ML=GS1.2.1689298676.2.1.1689299692.60.0.0; Hm_token=dTRSA6BC3pEw3thc6n7nQrkkyXDaDxDF',
//       Referer: 'https://www.kuwo.cn/',
//       Cross: 'fd6dead94e72757de6acf8f65fa3ad8b',
//     },
//   });
//   const data = await r.json();
//   res.send(data);
// });

app.get('/get', async (req, res) => {
  const url = req.query.url;
  const query = { ...req.query };
  const queryString = new URLSearchParams(Object.entries(query)).toString();
  let data = await getApi(url, queryString);
  if (tokenIsInvalid(data)) {
    await refreshCookies();
    data = await getApi(url, queryString);
  }
  res.send(data);
});

const port = process.env.PORT || 80;

async function bootstrap() {
  app.listen(port, () => {
    console.log('启动成功', port);
  });
}

bootstrap();
